import axios, { AxiosError, AxiosProgressEvent, Method, RawAxiosRequestHeaders } from 'axios'
import { showFailToast } from 'vant'

interface SomeAx<T = any> {
  data?: T,
  params?: T,
  headers?: RawAxiosRequestHeaders,
  onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;
}
export let baseUrl = "http://192.168.0.92:9101"
// production
// console.log(import.meta.env.MODE);
if (process.env.NODE_ENV === 'production') {
  baseUrl = "https://microservice.kasiasafe.top:5443/"
}
console.log(baseUrl);

function getToken() {
  return window.sessionStorage.getItem("token")
}

type ResloveFun = (value: any) => void;

export function AxiosQ(method: Method, url: string, some: SomeAx) {
  axios.defaults.baseURL = baseUrl
  if (some.headers == undefined) {
    some.headers = {
      "Authorization": getToken()
    }
  } else {
    if (some.headers["Authorization"] == undefined) {
      some.headers["Authorization"] = getToken()
    }
  }

  return new Promise((reslove: ResloveFun, reject: ResloveFun) => {
    axios.request({
      method: method,
      data: some.data,
      params: some.params,
      headers: some.headers,
      url: url,
      onUploadProgress: some.onUploadProgress,
    }).then(res => {
      if (res.status == 200) {
        if (res.data.code == 204) {
          showFailToast({
            message: "token fail",
          })

        } else {
          reslove(res.data)
        }
      } else {
        showFailToast({
          message: res.status.toString() + res.data.toString(),
        })
        reject(res.status)
      }
    }).catch((err: AxiosError) => {
      let msg = err.message

      if (err.response && err.response.data) {
        if ((err.response.data as any).data) {
          msg = (err.response.data as any).data.toString()
        }
      }
      showFailToast({
        message: msg,
      })
      reject(err.response?.data)
    })
  })
}